package com.yhh.college_information_platform.controller;

import com.yhh.college_information_platform.annotation.PublicAccess;
import com.yhh.college_information_platform.annotation.RequireAuth;
import com.yhh.college_information_platform.common.PageResult;
import com.yhh.college_information_platform.common.Result;
import com.yhh.college_information_platform.dto.CommentDTO;
import com.yhh.college_information_platform.dto.CommentQueryDTO;
import com.yhh.college_information_platform.service.CommentService;
import com.yhh.college_information_platform.vo.CommentVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 评论Controller
 *
 * @author yhh
 * @date 2025-10-26
 */
@Slf4j
@RestController
@RequestMapping("/comment")
public class CommentController {
    
    @Autowired
    private CommentService commentService;
    
    /**
     * 发布评论（需要登录）
     */
    @RequireAuth
    @PostMapping("/publish")
    public Result<Long> publishComment(@Valid @RequestBody CommentDTO commentDTO, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        
        // 兜底：从请求头解析 token 获取 userId
        if (userId == null) {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            try {
                com.yhh.college_information_platform.utils.JwtUtil jwtUtil =
                        org.springframework.web.context.support.WebApplicationContextUtils
                                .getRequiredWebApplicationContext(request.getServletContext())
                                .getBean(com.yhh.college_information_platform.utils.JwtUtil.class);
                if (token != null && jwtUtil.validateToken(token)) {
                    userId = jwtUtil.getUserIdFromToken(token);
                }
            } catch (Exception ignore) {}
        }
        
        Long commentId = commentService.publishComment(commentDTO, userId);
        return Result.success(commentId);
    }
    
    /**
     * 删除评论（需要登录）
     */
    @RequireAuth
    @DeleteMapping("/{commentId}")
    public Result<Void> deleteComment(@PathVariable Long commentId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        
        // 兜底：从请求头解析 token 获取 userId
        if (userId == null) {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            try {
                com.yhh.college_information_platform.utils.JwtUtil jwtUtil =
                        org.springframework.web.context.support.WebApplicationContextUtils
                                .getRequiredWebApplicationContext(request.getServletContext())
                                .getBean(com.yhh.college_information_platform.utils.JwtUtil.class);
                if (token != null && jwtUtil.validateToken(token)) {
                    userId = jwtUtil.getUserIdFromToken(token);
                }
            } catch (Exception ignore) {}
        }
        
        commentService.deleteComment(commentId, userId);
        return Result.success();
    }
    
    /**
     * 获取评论列表（游客可访问）
     */
    @PublicAccess
    @GetMapping("/page")
    public Result<PageResult<CommentVO>> getCommentPage(@Valid CommentQueryDTO queryDTO, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        
        PageResult<CommentVO> pageResult = commentService.getCommentPage(queryDTO, userId);
        return Result.success(pageResult);
    }
    
    /**
     * 点赞评论（需要登录）
     */
    @RequireAuth
    @PostMapping("/like/{commentId}")
    public Result<Void> likeComment(@PathVariable Long commentId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        
        // 兜底：从请求头解析 token 获取 userId
        if (userId == null) {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            try {
                com.yhh.college_information_platform.utils.JwtUtil jwtUtil =
                        org.springframework.web.context.support.WebApplicationContextUtils
                                .getRequiredWebApplicationContext(request.getServletContext())
                                .getBean(com.yhh.college_information_platform.utils.JwtUtil.class);
                if (token != null && jwtUtil.validateToken(token)) {
                    userId = jwtUtil.getUserIdFromToken(token);
                }
            } catch (Exception ignore) {}
        }
        
        commentService.likeComment(commentId, userId);
        return Result.success();
    }
    
    /**
     * 取消点赞评论（需要登录）
     */
    @RequireAuth
    @DeleteMapping("/like/{commentId}")
    public Result<Void> unlikeComment(@PathVariable Long commentId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        
        // 兜底：从请求头解析 token 获取 userId
        if (userId == null) {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            try {
                com.yhh.college_information_platform.utils.JwtUtil jwtUtil =
                        org.springframework.web.context.support.WebApplicationContextUtils
                                .getRequiredWebApplicationContext(request.getServletContext())
                                .getBean(com.yhh.college_information_platform.utils.JwtUtil.class);
                if (token != null && jwtUtil.validateToken(token)) {
                    userId = jwtUtil.getUserIdFromToken(token);
                }
            } catch (Exception ignore) {}
        }
        
        commentService.unlikeComment(commentId, userId);
        return Result.success();
    }
    
    /**
     * 判断是否点赞评论（需要登录）
     */
    @RequireAuth
    @GetMapping("/like/check/{commentId}")
    public Result<Boolean> isCommentLiked(@PathVariable Long commentId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        
        Boolean isLiked = commentService.isCommentLiked(commentId, userId);
        return Result.success(isLiked);
    }
}

